﻿namespace SLClient.Extension
{
    using System;
    using System.Reflection;
    using System.ServiceModel;
    using System.ServiceModel.Channels;
    using System.Xml.Linq;

    public class WCFServicesUtil<T> where T: class
    {
        public static string WcfAddress;

        static WCFServicesUtil()
        {
            string s = XElement.Load("DeployXML.xml").Attribute("Address").Value;
            WCFServicesUtil<T>.WcfAddress = XElement.Load("DeployXML.xml").Attribute("Address").Value;
        }

        public static T GetInstance(ServiceType serviceType)
        {
            T local = default(T);
            string serviceAddress = WCFServicesUtil<T>.GetServiceAddress(serviceType);
            if (string.IsNullOrEmpty(serviceAddress))
            {
                return default(T);
            }
            object[] parameters = new object[2];
            BasicHttpBinding binding = new BasicHttpBinding();
            binding.MaxReceivedMessageSize=0x7fffffff;
            binding.MaxBufferSize=0x7fffffff;
            binding.CloseTimeout=new TimeSpan(0, 1, 30);
            binding.OpenTimeout=new TimeSpan(0, 1, 30);
            binding.ReceiveTimeout=new TimeSpan(0, 3, 30);
            binding.SendTimeout=new TimeSpan(0, 1, 0);
            EndpointAddress address = new EndpointAddress(new Uri(serviceAddress, UriKind.Absolute), new AddressHeader[0]);
            parameters[0] = binding;
            parameters[1] = address;
            ConstructorInfo constructor = null;
            try
            {
                Type[] types = new Type[] { typeof(Binding), typeof(EndpointAddress) };
                constructor = typeof(T).GetConstructor(types);
            }
            catch (Exception)
            {
                return default(T);
            }
            if (constructor != null)
            {
                local = (T) constructor.Invoke(parameters);
            }
            return local;
        }

        public static string GetServiceAddress(ServiceType serviceType)
        {
            return WCFServicesUtil<T>.WcfAddress;
        }
    }
}

